<template>
	<z-paging ref="paging" v-model="dataList" @query="queryList">
		<view class="relative">
			<view style="z-index:0;position:absolute;left:-17px;right:-17px;top:-17px;bottom:-17px;height:225px;">
				<image v-if="merchantInfo" class="w-full h-full" mode="aspectFill" :src="homeBackgroundImage"></image>
			</view>
			<uni-nav-bar ref="navBar" fixed statusBar :border="false" backgroundColor="transparent" @clickLeft="goBack">
				<template v-slot:left>
					<image class="size-32" src="@/static/svg/icon-back.svg" />
				</template>
			</uni-nav-bar>
			<view class="bg-default" style="position:absolute;top:200px;width:100%;border-top-left-radius:12px;border-top-right-radius:12px;">
				<view v-if="merchantInfo" class="mx-16 flex-col">
					<view class="flex justify-between flex-shrink">
						<image class="radius-4" style="width:60px;height:60px;margin-top:-15px;" :src="merchantInfo.logo"></image>
						<view class="flex center">
							<template v-if="!isYourSelf">
								<view v-if="merchantInfo.subscribeState===1" class="flex-col center mt-7 mr-22" @click.stop="toSubscribe">
									<image class="size-24" src="@/static/svg/activity/icon-unsubscribe.svg"></image>
									<text class="fs-10 text-color-hint">订阅</text>
								</view>
								<view v-else class="flex-col center mt-7 mr-22" @click.stop="toCancelSubscribe">
									<image class="size-24" src="@/static/svg/activity/icon-subscribe.svg"></image>
									<text class="fs-10 text-color-hint">取消订阅</text>
								</view>
							</template>
							<view class="flex-col center mt-7" @click="toShare">
								<image class="size-24" src="@/static/svg/activity/icon-share.svg"></image>
								<text class="fs-10 text-color-hint">分享</text>
							</view>
						</view>
					</view>
					<view class="mt-12 flex justify-between item-center flex-shrink">
						<view class="flex-1 w-0 mr-50">
							<view class="fs-16 text-color-regular font-semibold">{{merchantInfo.businessShortName}}</view>
							<view class="mt-4 fs-12 text-color-hint">{{merchantInfo.subscribeCount}}人订阅</view>
						</view>
						<view v-if="merchantInfo" class="flex-shrink">
							<view v-if="isYourSelf" class="inline-flex center radius-16 bg-primary px-8 py-4" @click="toEdit">
								<image class="size-14 mr-4" src="@/pagesA/static/svg/icon-edit.svg"></image>
								<text class="fs-10 text-white">编辑主页</text>
							</view>
							<view v-if="merchantInfo.agentApplyState === 1 && !isYourSelf" class="distribution-btn" @click="toApply">申请分销</view>
							<view v-if="merchantInfo.agentApplyState === 2" class="distribution-btn" @click="clickApply">申请中</view>
							<view v-if="merchantInfo.agentApplyState === 3" class="fs-12">已成为经纪人</view>
						</view>
					</view>
					<view @click="toEdit">
						<view v-if="merchantInfo.introduction" class="mt-12 flex flex-shrink info-text">
							<!-- <image class="size-12 mr-4 mt-3 flex-shrink leading-17" src="@/pagesA/static/svg/introduction.svg"></image> -->
							<view style="white-space: pre-wrap;" :class="showAll ? '' : 'three-lines-ellipsis'" class="flex-1 mr-12 fs-12 text-color-hint leading-17">{{merchantInfo.businessIntroductions.filter(it => it.type === 1).map(it => it.content).join('')}}</view>
							<image :style="showAll ? 'transform: rotate(-90deg);' : 'transform: rotate(90deg);'" class="flex-shrink size-12 mt-10" src="@/static/svg/icon-arrow-right.svg" @click.stop="showAll = !showAll"></image>
						</view>
						<view v-if="medias && medias.length" class="mt-8 mr-16 flex-shrink">
							<template v-for="(item, i) in medias.filter((it, index) => index < 4)" :key="i">
								<image
									v-if="item.type===2"
									class="radius-4 mr-8"
									style="width:60px;height:60px;"
									:show-menu-by-longpress="true"
									:src="item.content"
									@click.stop="toPreview(item.content, i, medias)"
								></image>
								<view
									v-else-if="item.type===3"
									class="relative inline-flex center mr-8"
									@click.stop="toPreview(item.content, i, medias)"
								>
									<video
										class="radius-4"
										style="width:60px;height:60px;"
										:src="item.content"
										:autoplay="false"
										:muted="true"
										:show-center-play-btn="false"
										:show-fullscreen-btn="false"
										:enable-progress-gesture="false"
										:show-play-btn="false"
										:enable-play-gesture="true"
										:controls="false"
									></video>
									<image class="size-24 absolute" src="@/static/svg/publish/icon-play.svg"></image>
								</view>
							</template>
						</view>
						<view v-if="merchantInfo.position" class="mt-12 flex item-center flex-shrink">
							<image class="size-12 mr-4 flex-shrink leading-17" src="@/pagesA/static/svg/location.svg"></image>
							<view class="flex-1 text-cut fs-12 text-color-hint leading-17">{{merchantInfo.position}}</view>
						</view>
						<view v-if="!isYourSelf && merchantInfo.pointsMallState === 1" class="mall-tip flex item-center justify-between px-16 py-8 mt-12" @click="toMall">
							<view class="flex item-center">
								<image src="@/pagesA/static/image/mall.png" class="size-20 mr-8"></image>
								<view class="fs-14 color-primary">积分商城</view>
							</view>
							<view class="fs-12" v-if="merchantInfo.myRemainPoint > 0">可用<text class="fs-16 color-primary font-bold">{{merchantInfo.myRemainPoint}}</text>积分 ></view>
							<view class="fs-12" v-else>超值奖品等你来兑 ></view>
						</view>
					</view>
					<view class="mt-16 radius-12 bg-white flex-col">
						<search-bar v-model="queryParams.activeTitle" @search="onSearch" @clean="onClean" placeholder="搜活动"></search-bar>
						<view class="h-1 bg-default flex-shrink"></view>
						<view v-if="merchantInfo.agentState===2" class="flex h-47 fs-16">
							<view class="flex-1 flex center" @click="onTabClick('type', 1)">
								<text
									class="h-full"
									:class="queryParams.type===1?'color-primary font-semibold':'text-color-hint'"
									style="line-height:47px;"
									:style="queryParams.type===1?'border-bottom:2px solid #FA4543;':''"
								>全部活动</text>
							</view>
							<view class="flex-1 flex center" @click="onTabClick('type', 2)">
								<text
									class="h-full"
									:class="queryParams.type===2?'color-primary font-semibold':'text-color-hint'"
									style="line-height:47px;"
									:style="queryParams.type===2?'border-bottom:2px solid #FA4543;':''"
								>可推广的活动</text>
							</view>
						</view>
						<view v-else class="flex h-47 fs-16">
							<view class="flex-1 flex center" @click="onTabClick('sort', 1)">
								<text
									class="h-full"
									:class="queryParams.sort===1?'color-primary font-semibold':'text-color-hint'"
									style="line-height:47px;"
									:style="queryParams.sort===1?'border-bottom:2px solid #FA4543;':''"
								>默认</text>
							</view>
							<view class="flex-1 flex center" @click="onTabClick('sort', 2)">
								<text
									class="h-full"
									:class="queryParams.sort===2?'color-primary font-semibold':'text-color-hint'"
									style="line-height:47px;"
									:style="queryParams.sort===2?'border-bottom:2px solid #FA4543;':''"
								>销量</text>
							</view>
						</view>
						<view class="h-1 bg-default flex-shrink"></view>
						<view v-if="dataList && dataList.length">
							<template v-for="(item,i) in dataList" :key="`item-${i}`">
								<ActivityListItem
									:data="item"
									:isYourSelf="isYourSelf"
									@onDelete="onDelete(i)"
								></ActivityListItem>
								<view v-if="i!==dataList.length-1" :key="`line-${i}`" class="h-1 bg-default flex-shrink"></view>
							</template>
						</view>
						<view v-else class="py-50 bg-default">
							<view v-if="!loading" class="flex-col center h-full">
								<image style="width:136px;height:136px;" src="@/static/svg/empty-activity.svg"></image>
								<text class="mt-4 fs-12 text-color-regular font-normal text-center">暂无活动</text>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<template #empty>
			<view></view>
		</template>
		<template #bottom>
			<view :style="`height:${safeAreaBottom}px;`"></view>
		</template>
		<share-homepage v-if="showSharePopup" :id="id" :show="showSharePopup" @onClose="showSharePopup=false"></share-homepage>
	</z-paging>
</template>

<script setup name="MerchantHomePage">
	/**
	 * 策划人主页
	 */
	import { onLoad, onShareAppMessage } from '@dcloudio/uni-app'
	import {
		computed,
		onMounted,
		onUnmounted,
		ref,
		unref,
		watch
	} from 'vue'
	import { useUserStore } from '@/stores/modules/user.js'
	import { getHomePageApi, pageHomeActiveApi,getByInviteCode, businessSubscribeUpdateStateApi } from '@/api/business.js'
	import ActivityListItem from './components/ActivityListItem.vue'
	import { parseScene, modelShowToast } from '@/utils/index.js'
	const userStore = useUserStore()
	
	const navBar = ref(null)
	const showAll = ref(false)
	
	const navBarHeight = computed(() => {
		const statusBarHeight = uni.getWindowInfo().statusBarHeight
		const navigationBarHeight = statusBarHeight + (navBar.value && navBar.value.height || 0)
		return navigationBarHeight
	})
	const safeAreaBottom = computed(() => {
		return uni.getSystemInfoSync().safeAreaInsets && uni.getSystemInfoSync().safeAreaInsets.bottom || 0
	})
	
	const toApply = () => {
		uni.navigateTo({
			url: `/pagesH/agentApply?id=${id.value}&name=${merchantInfo.value.businessShortName}&avatar=${merchantInfo.value.logo}`
		})
	} 
	
	const clickApply = () => {
		uni.showToast({
			icon: 'none',
			title: '请等待商家审核'
		})
	} 
	
	const toSubscribe = () => {
		if (userStore.userInfo && userStore.userInfo.id) {
			businessSubscribeUpdateStateApi({
				businessId: merchantInfo.value.id,
				userId: userStore.userInfo.id,
				subscribeState: 1, // 订阅状态：1-订阅，2-取消订阅
			}).then(res => {
				if (res) {
					uni.showToast({
						icon: 'none',
						title: '订阅成功'
					})
				}
				getHomePage()
			}).catch(console.error)
		} else {
			uni.navigateTo({
				url: '/pagesA/login/login'
			})
		}
	}
	
	const toCancelSubscribe = () => {
		businessSubscribeUpdateStateApi({
			businessId: merchantInfo.value.id,
			userId: userStore.userInfo.id,
			subscribeState: 2, // 订阅状态：1-订阅，2-取消订阅
		}).then(res => {
			if (res) {
				uni.showToast({
					icon: 'none',
					title: '取消订阅成功'
				})
			}
			getHomePage()
		}).catch(console.error)
	}
	
	const goBack = () => {
		// 仅有一个页面时，返回首页
		if(getCurrentPages().length === 1) {
			uni.reLaunch({
				url: '/pages/home/home'
			})
			return
		}
		uni.navigateBack()
	}
	
	// 图片、视频全屏查看
	const toPreview = (src, i, arr = []) => {
		uni.navigateTo({
			url: '/pagesA/merchant/preview',
			success: (res) => {
				res.eventChannel.emit('acceptDataFromOpenerPage', {
					current: i,
					urls: arr
				})
			}
		})
	}

	const onTabClick = (key, val) => {
		if (queryParams.value[key] !== val) {
			queryParams.value[key] = val
			onSearch()
		}
	}
	
	const id = ref('')
	const merchantInfo = ref()
	const getHomePage = () => {
		if (id.value) {
			getHomePageApi(id.value).then(res => {
				merchantInfo.value = res
				try{
					merchantInfo.value.businessIntroductions = JSON.parse(res.introduction)
				}catch(e){
					merchantInfo.value.businessIntroductions = [{ type: 1, content: res.introduction }]
				}
			})
		}
	}
	// 背景图
	const homeBackgroundImage = computed(() => {
		return merchantInfo.value && merchantInfo.value.homeBackgroundImage || 'https://admin.huodongtg.com/static/image/bg_merchant_header.png'
	})
	// 策划人介绍图片、视频
	const medias = computed(() => {
		return merchantInfo.value && merchantInfo.value.businessIntroductions && merchantInfo.value.businessIntroductions.filter(it => it.type !== 1)
	})
	
	// 是否自己
	const isYourSelf = computed(() => {
		return !!(merchantInfo.value && userStore.userInfo && userStore.userInfo.businessInfo && merchantInfo.value.id === userStore.userInfo.businessInfo.id)
	})
	
	const toEdit = () => {
		if (!isYourSelf.value) return
		uni.navigateTo({
			url: `/pagesA/merchant/editHomePage?id=${id.value}`,
			events: {
				onUpdate() {
					getHomePage()
				}
			}
		})
	}
	
	const showSharePopup = ref(false)
	const toShare = () => {
		if (userStore.isLogin) {
			showSharePopup.value = true
		} else {
			uni.navigateTo({
				url: `/pagesA/login/login?from=${encodeURIComponent(`/pagesA/merchant/homepage?id=${id.value}`)}`,
				events: {
					onLoginSuccess() {
						getHomePage()
					}
				}
			})
		}
	}
	
	const queryParams = ref({
		businessId: '',
		activeTitle: '',
		pageNum: 1,
		pageSize: 10,
		sort: 1, // 排序：1-默认降序，2-销量降序
		type: 1, // 类型：1-全部活动，2-可推广的活动
	})
	const paging = ref(null)
	const dataList = ref([])
	const loading = ref(true)
	const queryList = (pageNo, pageSize) => {
		loading.value = true
		queryParams.value.pageNum = pageNo
		pageHomeActiveApi(unref(queryParams)).then(res => {
			paging.value.complete(res.list)
		}).finally(() => {
			loading.value = false
		})
	}
	
	const onSearch = () => {
		loading.value = true
		queryParams.value.pageNum = 1
		paging.value.reload()
	}
	
	const onClean = () => {
		loading.value = true
		queryParams.value.activeTitle = ''
		queryParams.value.pageNum = 1
		dataList.value = []
		paging.value.reload()
	}
	
	const onDelete = (i) => {
		dataList.value.splice(i, 1)
	}
	
	onShareAppMessage((options) => {
		console.log('分享好友', options, showSharePopup.value)
		showSharePopup.value = false
		const shareType = options.target.dataset.shareType
		if (shareType === 'activity') {
			console.log("options:",options);
			const url = options.target.dataset?.promotionType==='GROUP_BUY'
				?`/pagesB/activity/activity-group-buy`
				:`/pagesB/activity/activity`;
			return {
				title: options.target.dataset.title,
				path: `${url}?id=${options.target.dataset.activityId}&_from=homepage`,
				imageUrl: options.target.dataset.filepath
			}
		} else {
			return {
				title: shareData.value.businessShortName,
				path: `/pagesA/merchant/homepage?id=${id.value}`,
				imageUrl: options.target.dataset.filepath
			}
		}
	})
	const incode = ref('')
	const codeInner = ref({})
	const getInner = async () => {
		let result = await getByInviteCode({
			inviteCode: incode.value
		})
		if (result) {
			codeInner.value = result
			modelShowToast({
				title: '申请已提交，待策划人审核',
				content:`稍后可前往【我的-角色管理-我的策划人】查看`,
				showCancel:false,
				confirmColor:'#FA4543'})
		}
	}
	const toMall = () => {
		uni.navigateTo({
			url: `/pagesF/merchantMall/index?id=${queryParams.value.businessId}`,
		})
	}
	onLoad((query) => {
		console.log('策划人主页', query, query.scene)
		id.value = query.id || query.code
		queryParams.value.businessId = +query.id || +query.code
		if(query.incode){
			incode.value = query.incode
			getInner()
		}
		// 扫码打开
		if (query.scene) {
			const scene = parseScene(query.scene)
			if (!query.id && scene.code) {
				id.value = scene.code
				queryParams.value.businessId = scene.code
			}
			if(!query.incode && scene.incode){
				getInner()
			}
		}
		getHomePage()
		uni.$on('updateHomePage', getHomePage)
	})
	
	onUnmounted(() => {
		uni.$off('updateHomePage', getHomePage)
	})
</script>
<style scoped lang="scss">
	.three-lines-ellipsis {
		word-break: break-all;
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 3;
	}
	.info-text{
		align-items: flex-end;
	}
	.mall-tip{
		background: #FFF0EA;
		border-radius: 8px;
	}
	.distribution-btn{
		font-weight: 400;
		font-size: 12px;
		color: #FFFFFF;
		border-radius: 16px;
		padding: 4px 8px;
		line-height: 14px;
		background: #00AEFF;
		text-align: center;
	}
</style>